<template>
  <el-tree
    ref="tree"
    :data="data"
    :show-checkbox="showCheckBox"
    :node-key="nodeKey"
    :props="props"
    :default-expand-all="defaultExpandAll"
    @check-change="bindChange"
  >
    <template #default="{ node, data }" v-if="isSlot">
      <slot :node="node" :data="data" />
    </template>
  </el-tree>
</template>

<script>
export default {
  name: 'TreeData',
  props:{
    // 树形节点所有数据
    data: {
      type: Array,
      default:()=>[]
    },
    // 已选中的树节点字段值
    value: {
      type: Array,
      default: ()=>[]
    },
    // 每个树节点用来作为唯一标识的属性，整棵树应该是唯一的
    nodeKey: {
      type: String,
      default: 'id'
    },
    props: {
      type: Object,
      default: ()=>{}
    },
    showCheckBox: {
      type: Boolean,
      default : false
    },
    // 是否使用插槽
    isSlot: {
      type: Boolean,
      default: false
    },
    // 是否展开所有节点
    defaultExpandAll: {
      type: Boolean,
      default: false
    }
  },
  watch:{
    value(n){
      this.setNode(n)
    }
  },
  methods:{
    setNode(items){
      this.$nextTick(()=>{
        const tree = this.$refs.tree;
        items.forEach(item=>{
          const node = tree.getNode(item);
          if (node.isLeaf) {
            //设置某个节点的勾选状态
            tree.setChecked(node, true);
          }
        })
      })
    },
    bindChange(){
      const {tree} = this.$refs;
      const ids = [...tree.getHalfCheckedKeys(), ...tree.getCheckedKeys()]
      this.$emit('update:value', ids);
    }
  },
}
</script>

<style scoped>
.el-tree {
  margin-top: 10px;
}
</style>
